//
//  PYImagePickerManager.swift
//  YuanJuBian
//
//  Created by PerhapYs on 2022/1/6.
//

import UIKit

func savePhotoToLibrary(image:UIImage){
    
    guard AuthorizationManager.isPhotoLibraryAllowed() else {
        return
    }
    UIImageWriteToSavedPhotosAlbum(image, nil,nil, nil)
}

class PYImagePickerManager : NSObject{
    
    var pickImageComplete : ((UIImage)->())?
    
    func choicePhotoWithType(type: UIImagePickerController.SourceType , completionBlock:@escaping ReturnValueBlock<UIViewController>){
        
        AuthorizationManager.requestPhotoLibraryAuthorization { status in
            
            var isUsable = false
            if #available(iOS 14, *) {
                if  status == .limited || status == .authorized{
                    isUsable = true
                }
            } else {
                if status == .authorized || status == .restricted{
                    isUsable = true
                }
            }
            if isUsable{
                
                if UIImagePickerController.isSourceTypeAvailable(type) {
                    let picker = UIImagePickerController.init()
                    picker.modalPresentationStyle = .fullScreen
                    picker.delegate = self//代理
                    picker.sourceType = type//来源
                    picker.allowsEditing = true
                    completionBlock(picker)
                    return
                }
            }

            let str: String?
            if type == UIImagePickerController.SourceType.camera {
                str = "摄像头不可用,可前往设置中，授权相机权限."
            }else
            {
                str = "相册不可用,可前往设置中，授权相册权限."
            }
            let alert = UIAlertController.init(title: "温馨提示", message: str, preferredStyle: .alert)
            let action = UIAlertAction.init(title: "知道了", style: .default) { action in
                alert.dismiss(animated: true, completion: nil)
            }
            alert.addAction(action)
            completionBlock(alert)
        }
    }
}

extension PYImagePickerManager : UINavigationControllerDelegate, UIImagePickerControllerDelegate{
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        picker.dismiss(animated: true, completion: nil)
        
        guard let block = self.pickImageComplete else {
            return
        }
        guard let image = info[UIImagePickerController.InfoKey.editedImage] else{
            return
        }
        guard let unwapImage = image as? UIImage else {
            return
        }
        block(unwapImage)
    }
}
